<template>
  <div class="table-box">
    <ProTable ref="proTable" title="用户列表" :columns="columns" :request-api="userApi.getUsers" :searchCol="4">
      <!-- Operation -->
      <template #operation="scope">
        <el-button type="primary" link @click="openRolesDialog(scope.row)" :disabled="disabled(scope.row)"
          >权限变更</el-button
        >
      </template>
    </ProTable>

    <!-- 权限变更弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="权限变更" width="500">
      <role-form :roles v-model="userForm" />
      <template #footer>
        <div class="">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import uploadApi from '@/apis/upload';
import userApi from '@/apis/user';
import type { UserApiType } from '@/apis/user/namespace';
import type { ColumnProps, ProTableInstance } from '@/components/proTable/interface';
import { PermissionsEnum } from '@/enum';
import { dayjs } from 'element-plus';
import RoleForm from './form/role-form.vue';

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: 'index', label: '序号', width: 80 },
  {
    prop: 'imgUrl',
    label: '头像',
    width: 74,
    align: 'center',
    render: (scope) => {
      return (
        <upload
          data={{ userId: scope.row.id }}
          imageUrl={scope.row.imgUrl ?? ''}
          api={uploadApi.uploadUserImg}
          borderRadius="50%"
          height="50px"
          width="50px"
          disabled={Boolean(scope.row.imgUrl)}
          onUpdate:imageUrl={() => {
            proTable.value?.search();
          }}
        />
      );
    },
  },
  { prop: 'name', label: '用户名', search: { el: 'input', tooltip: '支持模糊搜索：' }, width: 200 },
  { prop: 'email', label: '邮箱', search: { el: 'input' }, width: 200 },
  { prop: 'mobile', label: '手机号码', search: { el: 'input' }, width: 200 },
  {
    prop: 'roles',
    label: '角色权限',
    width: 200,
    render: (scope) => {
      const roles: string[] = scope.row?.roles?.map((role: UserApiType.Roles) => role.description);
      return (
        <div class="text-gray-500">
          {roles?.map((role, index) => (
            <el-tag type="success" size="small" class="mr-2" key={index}>
              {role}
            </el-tag>
          ))}
        </div>
      );
    },
  },
  {
    prop: 'createAt',
    label: '创建时间',
    width: 200,
    render: (scope) => {
      const date = dayjs(scope.row?.createAt ?? '')?.format('YYYY-MM-DD HH:mm:ss');
      return <div class="text-gray-500">{date}</div>;
    },
  },
  {
    prop: 'status',
    label: '用户状态',
    width: 200,
    fixed: 'right',
    render: (scope) => {
      return (
        <el-switch
          model-value={scope.row.status}
          active-text={scope.row.status ? '启用' : '禁用'}
          active-value={true}
          inactive-value={false}
          onClick={() => changeStatus(scope.row)}
        />
      );
    },
  },
  { prop: 'operation', label: '操作', fixed: 'right', width: 200, align: 'center' },
]);

// 禁用按钮
const disabled = (row: UserApiType.Info) => {
  return row.roles.some((role) => role.name === PermissionsEnum.SUPER_ADMIN);
};

// 选中用户的角色权限选项
const userForm = ref<UserApiType.ChangeRolesInterface>({
  userId: null,
  roles: [],
});

// 全部角色选项
const roles = ref<UserApiType.Roles[]>([]);
const getRoles = async () => {
  roles.value = await userApi.getRoles();
};

// 改变用户状态
const changeStatus = async (row: UserApiType.Info) => {
  const params = { userId: row.id, status: !row.status };
  await userApi.updateStatus(params);
  proTable.value?.search();
};

// 打开弹窗框
const dialogFormVisible = ref(false);
const openRolesDialog = (row: UserApiType.Info) => {
  userForm.value.roles = row.roles.map((role) => role.id);
  userForm.value.userId = row.id;
  dialogFormVisible.value = !dialogFormVisible.value;
};

// 提交权限变更
const handleSubmit = async () => {
  await userApi.updateRoles(userForm.value);
  dialogFormVisible.value = false;
  proTable.value?.search();
};

onMounted(() => {
  getRoles();
});
</script>

<style scoped lang="scss"></style>
